import svar
import numpy as np
import cv2
import time
import json
import requests
import os

rtmv=svar.load('svar_rtmv')
rtmv.set_gps_rad(True)
options={"ip":"/data/zhaoyong/Dataset/Onboard/1610609911.69514.rtmv","port":1212,"skip":1}

dataset=rtmv.DatasetNetwork(options)
last_time=0
latest_fr=None

qglopm=svar.load('svar_qglopm')

qapp=qglopm.QApplication()

vis2d= qglopm.Visualizer2D({})
vis2d.show()

def gaode_url(x,y,z):
  return "http://wprd03.is.autonavi.com/appmaptile?style=7&x=%d&y=%d&z=%d" % (x,y,z)

base_des={"type":"livelayer","manager":gaode_url,"cache_folder":"/tmp"}
base_layer=vis2d.addLayer("base",base_des)

#live_des={"type":"livelayer","manager":"http://192.168.1.231:80/dom","cache_folder":"/tmp"}
#live_layer=vis2d.addLayer("live",live_des)

image_overlayerdes={"type":"imageoverlayer",
                    "image":"/data/zhaoyong/Dataset/DroneMap2/mavic-garden/thumbnail/DJI_0002.JPG"}
image_overlayerdes["coordinates"]=[[34.184040083333329,108.84807444444444],
                                   [34.184040083333329,108.84957444444444],
                                   [34.183040083333329,108.84907444444444],
                                   [34.183040083333329,108.84807444444444]]
image_overlayer=vis2d.addLayer("imageover",image_overlayerdes)


def post_liveframe(url,imagefile,jsonfile):
    f_json=open(jsonfile,'rb')
    f_img=open(imagefile, "rb")
    files={
        jsonfile : f_json,imagefile : f_img
       }
    try:
        r = requests.post(url, None, files=files)
        print(r.text)
    except:
        f_json.close()
        f_img.close()
        print("failed to post",imagefile)

def callback_frame(fr):
  if fr == None:
    return

  global latest_fr
  latest_fr=fr
 
  global last_time
  if fr.timestamp() < last_time+0.1:
    return
  last_time=fr.timestamp()

  image=fr.getImage(0,0)
  m= np.array(image)
  
  lt=rtmv.from_pixel_to_lla(fr,(0,0))
  rt=rtmv.from_pixel_to_lla(fr,(image.width(),0))
  rb=rtmv.from_pixel_to_lla(fr,(image.width(),image.height()))
  lb=rtmv.from_pixel_to_lla(fr,(0,image.height()))
  coordinates=[[lt.x,lt.y],[rt.x,rt.y],[rb.x,rb.y],[lb.x,lb.y]]
  print(coordinates)
  image_overlayer.set(image,coordinates)

sub_kf= rtmv.messenger.subscribe('UI.output.curframe',0,callback_frame)

while True:
  qapp.processEvents()
  time.sleep(0.01)



